package com.min.main.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.min.common.entity.MinReource;
import com.min.common.util.GsonUtil;
import com.min.main.constant.RedisKey;
import com.min.main.entity.MenuRoleEntity;
import com.min.main.entity.RoleUserEntity;
import com.min.main.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.min.main.entity.RoleEntity;
import com.min.main.dao.RoleDao;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 角色表
 *
 * @author fengt
 * @date 2021-06-23 11:41:08
 */
@Service
public class RoleService extends ServiceImpl<RoleDao, RoleEntity> {

    @Autowired
    RedisUtils redis;

    @Autowired
    MenuRoleService menuRoleService;

    @Autowired
    RoleUserService roleUserService;

    public List<RoleEntity> getByToken(String token) {
        String json = redis.get(RedisKey.TOKEN + token);
        return GsonUtil.fromJsonList(json, RoleEntity.class);
    }

    public List<MinReource> getMinResoures() {
        return this.baseMapper.getMinResoures();
    }

    public List<Long> getMenus(Long id) {
        return this.baseMapper.getMenus(id);
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean saveOrUpdateWithMenus(RoleEntity t) {

        if (menuRoleService.checkBounds(t.getMenuIdList())) {
            return false;
        }

        if (t.getId() != null && t.getId() > 0L) {
            menuRoleService.saveRoleMenus(t.getId(), t.getMenuIdList());
            this.updateById(t);
            return true;
        } else {
            if (this.save(t)) {
                menuRoleService.saveRoleMenus(t.getId(), t.getMenuIdList());
                return true;
            }
        }

        return false;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean removeWithMenus(Long roleId) {
        menuRoleService.remove(Wrappers.lambdaQuery(MenuRoleEntity.class).eq(MenuRoleEntity::getRoleId, roleId));
        roleUserService.remove(Wrappers.lambdaQuery(RoleUserEntity.class).eq(RoleUserEntity::getRoleId, roleId));
        this.removeById(roleId);
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean removeWithMenus(List<Long> roleIds) {
        for (Long roleId : roleIds) {
            this.removeWithMenus(roleId);
        }
        return true;
    }
}

